package com.abc.cloud.service.impl;
import java.util.Date;

import com.abc.cloud.common.exception.MyException;
import com.abc.cloud.common.utils.UserHolder;
import com.abc.cloud.dto.notice.NoticeDto;
import com.abc.cloud.dto.notice.PageDto;
import com.abc.cloud.entity.UserEntity;
import com.abc.cloud.service.UserNoticeService;
import com.abc.cloud.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.abc.cloud.common.utils.PageUtil;
import com.abc.cloud.common.utils.Query;

import com.abc.cloud.dao.NoticeDao;
import com.abc.cloud.entity.NoticeEntity;
import com.abc.cloud.service.NoticeService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;


@Slf4j
@Service("noticeService")
public class NoticeServiceImpl extends ServiceImpl<NoticeDao, NoticeEntity> implements NoticeService {

    @Autowired
    private UserNoticeService userNoticeService;

    @Autowired
    private UserService userService;

    @Override
    public PageUtil queryPage(Map<String, Object> params) {
        IPage<NoticeEntity> page = this.page(
                new Query<NoticeEntity>().getPage(params),
                new QueryWrapper<NoticeEntity>()
        );

        return new PageUtil(page);
    }

    @Override
    public void sendNotice(String title, String content, Long userId, String username, Long targetId, String targetUsername, Integer receiverType, Integer type) {
        NoticeEntity noticeEntity = new NoticeEntity();
        noticeEntity.setTitle(title);
        noticeEntity.setContent(content);
        noticeEntity.setCreaterId(userId);
        noticeEntity.setReceiverType(receiverType);
        noticeEntity.setType(type);
        noticeEntity.setTargetId(targetId);
        noticeEntity.setCreaterUsername(username);
        noticeEntity.setTargetUsername(targetUsername);
        this.baseMapper.insert(noticeEntity);

        // 保存该联系人消息的读取状态
        userNoticeService.saveNotice(targetId, noticeEntity.getId(), 1);
    }



    @Override
    public PageDto getList(@RequestParam Map<String, Object> params) {
        Integer pageSize = 10;
        Integer currPage = 1;
        boolean All = false;            //是否需要设置全部已读

        long userId = UserHolder.getUser().getId();
        if(params.get("isAll") != null){
            All = Boolean.parseBoolean(String.valueOf(params.get("isAll")));
        }

        if(params.get("pageSize") != null){
            pageSize = Integer.parseInt(String.valueOf(params.get("pageSize")));
        }
        if(params.get("currPage") != null){
            currPage = Integer.parseInt(String.valueOf(params.get("currPage")));
        }
        if(All){
            baseMapper.updateAllRead((short) 2,userId);
        }
        pageSize = pageSize > 0 ? pageSize : 1;
        Integer totalCount = baseMapper.getCount(userId);        //总记录数
        Integer totalPage = totalCount / pageSize + (totalCount%pageSize > 0 ? 1 : 0);       //总页数
        log.info("x = {},y = {},userId = {}", (currPage-1)*pageSize ,pageSize,userId);
        List<NoticeDto> noticeList = baseMapper.getList((currPage-1)*pageSize ,pageSize,userId);
        log.info("noticeList = {}",noticeList);
//        PageUtil page = new PageUtil(noticeList,pageSize,currPage,totalCount,totalPage);
        Integer count = baseMapper.getNotReadCount(userId);
        PageDto pageDto = new PageDto(noticeList,pageSize,currPage,totalCount,totalPage,count);
        return pageDto;
    }




    //    后台管理获取所有
    @Override
    public PageUtil getAllList(Map<String, Object> params) {
        Integer pageSize = 10;
        Integer currPage = 1;
        String searchContent = "";
        if(params.get("pageSize") != null){
            pageSize = Integer.parseInt(String.valueOf(params.get("pageSize")));
        }
        if(params.get("currPage") != null){
            currPage = Integer.parseInt(String.valueOf(params.get("currPage")));
        }
        if(params.get("searchContent") != null){
            searchContent = String.valueOf(params.get("searchContent"));
        }
        pageSize = pageSize > 0 ? pageSize : 1;
        Integer totalCount = baseMapper.getAllCount(searchContent);        //总记录数
        Integer totalPage = totalCount / pageSize + (totalCount%pageSize > 0 ? 1 : 0);       //总页数
        List<NoticeEntity> noticeList = baseMapper.getAllList((currPage-1)*pageSize ,pageSize,searchContent);
        return new PageUtil(noticeList,pageSize,currPage,totalCount,totalPage);

    }

    @Override
    public void updateNoticeStatus(List<Long> noticeIds, Integer status) {
        baseMapper.updateNoticeStatus(noticeIds,status);
    }

    @Override
    public boolean addNotice(Long userId, String username, String title, String content, String targetUsername, Integer receiverType, Integer type) {
        NoticeEntity notice = new NoticeEntity();
        notice.setCreaterId(userId);
        notice.setCreaterUsername(username);
        notice.setType(type);
        notice.setReceiverType(receiverType);
        notice.setTargetId(null);
        notice.setTargetUsername(targetUsername);
        notice.setTitle(title);
        notice.setContent(content);
        this.baseMapper.insert(notice);

        if (receiverType == 1){
            List<UserEntity> userEntityList = userService.list(new QueryWrapper<UserEntity>().eq("status", 1));
            if (userEntityList.size() == 0){
                return true;
            }
            userNoticeService.saveAllUserNotice(userEntityList, notice.getId(), 1);
        }
        else{
            UserEntity one = userService.getOne(new QueryWrapper<UserEntity>().eq("username", targetUsername).eq("status", 1));
            if (one == null){
                throw new MyException("该用户不存在");
            }
            notice.setTargetId(one.getId());
            this.baseMapper.updateById(notice);
            userNoticeService.saveNotice(one.getId(), notice.getId(), 1);
        }

        return true;
    }
}